package com.zh.security.handler;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 * @Description: 自定义登录成功跳转处理器
 * @ClassName MyAuthenticationSuccessHandler
 * @date: 2021.10.17 17:47
 * @Author: zhanghang
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	private String url;



	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
		System.out.println(httpServletRequest.getRemoteAddr());

		// authentication 认证信息
		// 获取认证权限
		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
		Object credentials = authentication.getCredentials();
		Object details = authentication.getDetails();
		// 获取UserDetailsService 返回封装的User对象
		User user = (User) authentication.getPrincipal();
		System.out.println("user: "+user);
		System.out.println("authorities: "+authorities);
		System.out.println("credentials: "+credentials);
		System.out.println("details: "+details);

		// 使用重定向跳转url
		httpServletResponse.sendRedirect(url);
	}

	public MyAuthenticationSuccessHandler(String url){
		this.url = url;
	}

}
